#ifndef LOGHANDLER_HPP
#define LOGHANDLER_HPP

#if (_MSC_VER >= 1300)
#pragma once
#endif // (_MSC_VER >= 1300)

#include <fstream>
#include <string>
#include <vector>

class CFile
	{
	std::string m_filename;

	public:
		CFile(std::string const & file_name)
			: m_filename(file_name) 
			{}
		virtual ~CFile() {}

		void clear()
			{
			std::ofstream file_stream(m_filename.c_str(), std::ios_base::trunc);
			}

		template <typename T> bool write(T const & data)
			{
			std::ofstream file_stream(m_filename.c_str(), std::ios_base::app); // Set the append flag
			if (!file_stream) // Use operator! to check file-bit-state (fail & bad-bit)
				return false;

			file_stream << data;
			return !!file_stream; // writing data successful? operator void* or (return !!file_stream) operator!
			}
	};

class CLogHandler
	{
	private:
		std::vector<std::string> m_tags;
		std::size_t m_layer;

	protected:
		CFile* m_ptrFile;

	public:
		CLogHandler(std::string const & filename)
			: m_layer(0)
			{
			m_ptrFile = new CFile(filename);
			m_ptrFile->clear();
			m_ptrFile->write("<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n");
			}
		void close_tag_tree()
			{
			if (m_tags.empty() == true || m_layer == 0) return; // any tag_tree exist?

			--m_layer;
			m_ptrFile->write(std::string(m_layer, '\t') + "</" + m_tags[m_tags.size() - 1] + ">\n" );
			m_tags.pop_back();
			}
		virtual ~CLogHandler()
			{
			while (m_tags.empty() == false)
				{
				close_tag_tree();
				}

			delete m_ptrFile;
			}

		void add_tag_tree(std::string const & tag_name)
			{
			m_ptrFile->write(std::string(m_layer, '\t') + '<' + tag_name + ">\n");
			m_tags.push_back(tag_name);
			++m_layer;
			}

		template <typename T> 
		void add_tag(std::string const& name, T const & data)
			{
			m_ptrFile->write(std::string(m_layer, '\t') + '<' + name + '>');
			m_ptrFile->write<T>(data);
			m_ptrFile->write(std::string("</") + name + ">\n");
			}

		void add_comment(std::string const& comment)
			{
			m_ptrFile->write(std::string(m_layer, '\t') + "<!-- " + comment + " -->\n");
			}


	};

#endif // LOGHANDLER_HPP